<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addOrEditRole()">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- table区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom',index1 === 0? 'bdtop' : '' ,'vcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '':'bdtop','vcenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="5">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightsById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-tag
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                      :class="[index3 === 0 ? '':'bdtop']"
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="索引"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="248">
          <template v-slot="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                @click="addOrEditRole(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              slot="reference"
              @click="deleteRole(scope.row)"
            ></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close="closeAddOrEditRoleForm"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addOrEditRoleForm"
        :rules="addOrEditRoleFormRules"
        ref="addOrEditRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addOrEditRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addOrEditRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddOrEditRoleForm">取 消</el-button>
        <el-button type="primary" @click="addOrEditRoleBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="showSetRightsDialog"
      @close="closeshowSetRightsDialog"
      ref="rightsDialogRef"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultKeys"
        ref="rightsDialogRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeshowSetRightsDialog">取 消</el-button>
        <el-button type="primary" @click="setCurrentRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表
      rolesList: [],
      // 控制权限分配对话框
      showSetRightsDialog: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的权限值
      defaultKeys: [],
      // 当前角色id
      currentRoleId: '',
      // 添加角色对话框控制
      addRoleDialogVisible: false,
      // 添加/编辑角色列表
      addOrEditRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色规则
      addOrEditRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '长度在  到 15 个字符内',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  mounted () {},
  methods: {
    // 获取角色权限列表
    async getRolesList () {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.rolesList = res.data
    },
    // 取消角色权限
    async removeRightsById (userInfo, rightId) {
      const confirmRes = await this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch((err) => err)
      if (confirmRes !== 'confirm') {
        return this.$message({
          type: 'warning',
          message: '取消删除'
        })
      }
      const res = await this.$http.delete(
        `roles/${userInfo.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.$message({
        type: 'success',
        message: res.meta.msg
      })

      userInfo.children = res.data
    },
    // 打开权限分配列表
    async showSetRightDialog (currentRole) {
      this.currentRoleId = currentRole.id
      this.showSetRightsDialog = true
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.rightsList = res.data
      this.getDefaultKeys(currentRole, this.defaultKeys)
    },
    // 递归方式获取默认权限
    getDefaultKeys (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach((item) => {
        this.getDefaultKeys(item, arr)
      })
    },
    // 取消分配权限
    closeshowSetRightsDialog () {
      this.defaultKeys = []
      this.showSetRightsDialog = false
    },
    // 确认分配权限
    async setCurrentRoleRights () {
      const keys = [
        ...this.$refs.rightsDialogRef.getCheckedKeys(),
        ...this.$refs.rightsDialogRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.currentRoleId}/rights`, {
        rids: keysStr
      })
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }

      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      this.showSetRightsDialog = false
      this.getRolesList()
    },
    // 打开添加/编辑角色对话框
    addOrEditRole (currentRole) {
      if (currentRole) {
        this.currentRoleId = currentRole.id
        this.addOrEditRoleForm = currentRole
      }
      this.addRoleDialogVisible = true
    },
    // 关闭添加角色对话框
    closeAddOrEditRoleForm () {
      this.addRoleDialogVisible = false
      this.addOrEditRoleForm = {}
      this.currentRoleId = ''
    },
    // 确认添加角色按钮
    addOrEditRoleBtn () {
      if (!this.currentRoleId) {
        this.$refs.addOrEditRoleFormRef.validate(async (valid) => {
          if (!valid) {
            return this.$message({
              type: 'error',
              message: '请确认角色信息完整'
            })
          }
          const res = await this.$http.post('roles', this.addOrEditRoleForm)
          if (res.meta.status !== 201) {
            return this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
          this.$message({
            type: 'success',
            message: res.meta.msg
          })

          this.addRoleDialogVisible = false
          this.getRolesList()
        })
      } else {
        this.$refs.addOrEditRoleFormRef.validate(async (valid) => {
          if (!valid) {
            return this.$message({
              type: 'error',
              message: '请确认角色信息完整'
            })
          }
          const res = await this.$http.put('roles/' + this.currentRoleId, this.addOrEditRoleForm)
          if (res.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
          this.$message({
            type: 'success',
            message: res.meta.msg
          })

          this.addRoleDialogVisible = false
          this.getRolesList()
        })
      }
    },
    // 删除角色
    async deleteRole (userInfo) {
      const res = await this.$http.delete('roles/' + userInfo.id)
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin: 8px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
